<template>
  <el-container>
    <el-aside width="200px">
      <el-scrollbar wrap-style="height:calc(100vh - 175px);">
        <el-tree
          style="max-width: 600px"
          :props="orgTreeProps"
          :load="loadNode"
          node-key="id"
          :default-expanded-keys="expandedKeys"
          :expand-on-click-node="false"
          lazy
          @node-click="clickTreeNode"
        >
          <template #default="{ node }">
            <template v-if="node.data.typeIcon">
              <Icon
                :icon="node.data.typeIcon"
                :color="node.data.typeColor"
                :hoverColor="node.data.typeColor"
              />
            </template>
            <template v-else>
              <Icon icon="octicon:organization" color="#008000" hoverColor="#008000" />
            </template>
            <span class="ml-1">{{ node.label }}</span>
          </template>
        </el-tree>
      </el-scrollbar>
    </el-aside>
    <WsmTable
      ref="table"
      v-model="queryFormType"
      load-url="/rbac-server/rbac/user/page"
      :query-type="queryFormType"
      :change-load="true"
    >
      <template #title>{{ title }}</template>
      <template #query="{ data }">
        <el-form-item :label="t('rbac.user.userName')">
          <el-input v-model="data.userName.value" />
        </el-form-item>
        <el-form-item :label="t('rbac.user.idCard')">
          <el-input v-model="data.idCard.value" />
        </el-form-item>
        <el-form-item :label="t('rbac.user.userState')">
          <el-radio-group v-model="data.userState.value">
            <el-radio value="">{{ t('rbac.user.all') }}</el-radio>
            <el-radio value="0">{{ t('rbac.user.disable') }}</el-radio>
            <el-radio value="1">{{ t('rbac.user.enable') }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </template>
      <template #button="{ row }">
        <el-button
          type="primary"
          v-hasPermi="'add'"
          @click="addForm.show()"
          v-if="initData.orgId != 'root'"
          >{{ t('common.add') }}</el-button
        >
        <template v-if="row">
          <template v-if="row.userId != 'administrator'">
            <el-button v-hasPermi="'update'" @click="update(row.userId)" type="primary">{{
              t('common.update')
            }}</el-button>
            <template v-if="row.userState">
              <el-button v-hasPermi="'check'" @click="check(row.userId)" type="danger">{{
                t('rbac.user.disable')
              }}</el-button>
            </template>
            <template v-else>
              <el-button v-hasPermi="'check'" @click="check(row.userId)" type="success">{{
                t('rbac.user.enable')
              }}</el-button>
            </template>
          </template>
          <el-button v-hasPermi="'bind'" @click="bind(row.userId)" type="warning">{{
            t('common.bind')
          }}</el-button>
        </template>
      </template>
      <template #column>
        <el-table-column prop="userState" :label="t('rbac.user.userState')" width="70">
          <template #default="scope">
            <template v-if="scope.row.userState">
              <el-tag effect="dark" type="success">{{ t('rbac.user.enable') }}</el-tag>
            </template>
            <template v-else>
              <el-tag effect="dark" type="danger">{{ t('rbac.user.disable') }}</el-tag>
            </template>
          </template>
        </el-table-column>
        <el-table-column prop="userCode" :label="t('rbac.user.userCode')" width="120" />
        <el-table-column prop="typeName" :label="t('rbac.user.userType')" width="120" />
        <el-table-column prop="userName" :label="t('rbac.user.userName')" width="100" />
        <el-table-column prop="idCard" :label="t('rbac.user.idCard')" />
        <el-table-column prop="mobile" :label="t('rbac.user.mobile')" width="120" />
        <el-table-column prop="eMail" :label="t('rbac.user.eMail')" width="240" />
      </template>
    </WsmTable>
  </el-container>

  <WsmForm
    ref="addForm"
    v-model="addData"
    submit-url="/rbac-server/rbac/user/add"
    label-width="100px"
    :init-data="initData"
    :title="t('rbac.user.addTitle')"
    @success="flushed"
  >
    <template #default="{ form }">
      <el-row>
        <el-col :span="12">
          <el-form-item prop="userCode" :label="t('rbac.user.userCode')">
            <el-input v-model="form.userCode" :placeholder="t('rbac.user.userCode')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="userType" :label="t('rbac.user.userType')">
            <el-select v-model="form.userType" :placeholder="t('rbac.user.userType')">
              <el-option
                v-for="item in options"
                :key="item.id"
                :label="item.typeName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item prop="userName" :label="t('rbac.user.userName')">
            <el-input v-model="form.userName" :placeholder="t('rbac.user.userName')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="nickName" :label="t('rbac.user.nickName')">
            <el-input v-model="form.nickName" :placeholder="t('rbac.user.nickName')" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item prop="idCard" :label="t('rbac.user.idCard')">
            <el-input v-model="form.idCard" :placeholder="t('rbac.user.idCard')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="mobile" :label="t('rbac.user.mobile')">
            <el-input v-model="form.mobile" :placeholder="t('rbac.user.mobile')" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item prop="phone" :label="t('rbac.user.phone')">
            <el-input v-model="form.phone" :placeholder="t('rbac.user.phone')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="eMail" :label="t('rbac.user.eMail')">
            <el-input v-model="form.eMail" :placeholder="t('rbac.user.eMail')" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item prop="loginAccount" :label="t('rbac.user.loginAccount')">
            <el-input v-model="form.loginAccount" :placeholder="t('rbac.user.loginAccount')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="password" :label="t('rbac.user.password')">
            <el-input
              type="password"
              v-model="form.password"
              :placeholder="t('rbac.user.password')"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item prop="orId" :label="t('rbac.user.orId')">
            <el-checkbox-group v-model="form.orId">
              <el-checkbox
                v-for="item in orgRoleList"
                :key="item.id"
                :label="item.typeName"
                :value="item.id"
              >
                {{ item.typeName }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-col>
      </el-row>
    </template>
  </WsmForm>

  <WsmForm
    ref="updateForm"
    v-model="updateData"
    load-url="/rbac-server/rbac/user/get"
    submit-url="/rbac-server/rbac/user/update"
    label-width="100px"
    :init-data="initData"
    :title="t('rbac.user.updateTitle')"
    @success="flushed"
  >
    <template #default="{ form }">
      <el-row>
        <el-col :span="12">
          <el-form-item prop="userCode" :label="t('rbac.user.userCode')">
            <el-input v-model="form.userCode" :placeholder="t('rbac.user.userCode')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="userType" :label="t('rbac.user.userType')">
            <el-select v-model="form.userType" :placeholder="t('rbac.user.userType')">
              <el-option
                v-for="item in options"
                :key="item.id"
                :label="item.typeName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item prop="userName" :label="t('rbac.user.userName')">
            <el-input v-model="form.userName" :placeholder="t('rbac.user.userName')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="nickName" :label="t('rbac.user.nickName')">
            <el-input v-model="form.nickName" :placeholder="t('rbac.user.nickName')" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item prop="idCard" :label="t('rbac.user.idCard')">
            <el-input v-model="form.idCard" :placeholder="t('rbac.user.idCard')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="mobile" :label="t('rbac.user.mobile')">
            <el-input v-model="form.mobile" :placeholder="t('rbac.user.mobile')" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item prop="phone" :label="t('rbac.user.phone')">
            <el-input v-model="form.phone" :placeholder="t('rbac.user.phone')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="eMail" :label="t('rbac.user.eMail')">
            <el-input v-model="form.eMail" :placeholder="t('rbac.user.eMail')" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item prop="orId" :label="t('rbac.user.orId')">
            <el-checkbox-group v-model="form.orId">
              <el-checkbox
                v-for="item in orgRoleList"
                :key="item.id"
                :label="item.typeName"
                :value="item.id"
              >
                {{ item.typeName }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-col>
      </el-row>
    </template>
  </WsmForm>

  <WsmForm
    ref="bindForm"
    v-model="bindData"
    load-url="/rbac-server/rbac/resource/getResourceUser"
    label-position="top"
    submit-url="/rbac-server/rbac/resource/updateResourceUser"
    :title="t('rbac.bindTitle')"
  >
    <template #default="{ form }">
      <el-form-item prop="resId" :label="t('rbac.bindResource')">
        <el-checkbox-group v-model="form.resId">
          <el-checkbox
            v-for="item in resources"
            :key="item.id"
            :label="item.resName"
            :value="item.id"
          >
            {{ item.resName }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
    </template>
  </WsmForm>
</template>
<script setup lang="ts">
import { WsmTable } from '@/components/WsmTable'
import { WsmForm } from '@/components/WsmForm'
import { QueryFormType, QueryType } from '@/components/WsmTable/src/types'
import { computed, reactive, ref } from 'vue'
import { useI18n } from '@/hooks/web/useI18n'
import { FormDataType } from '@/components/WsmForm/src/types'
import { getTreeChildApi } from '@/api/rbac/org'
import { checkstateApi } from '@/api/rbac/user'
import { listApi } from '@/api/rbac/usertype'
import type Node from 'element-plus/es/components/tree/src/model/node'
import { UserType } from '@/api/rbac/usertype/types'
import { useUserStore } from '@/store/modules/user'
import { OrgTreeDataType } from '../Org/types'
import { ResourceType } from '@/api/rbac/resource/types'
import { listResourceApi } from '@/api/rbac/resource'
import { OrgRoleType } from '@/api/rbac/orgrole/types'
import { getOrgRoleList } from '@/api/rbac/orgrole'

const options = ref<UserType[]>([])

const { t } = useI18n()

const userStore = useUserStore()
//列表标题
const orgName = ref(t('rbac.org.orgRoot'))

//新增表单对象
const addForm = ref()
const initData = ref({
  orgId: 'root',
  orId: []
})

const expandedKeys = ref(['root'])

const addData: FormDataType = reactive({
  orgId: 'root',
  loginAccount: '',
  userCode: '',
  userName: '',
  nickName: '',
  userType: '',
  idCard: '',
  mobile: '',
  phone: '',
  eMail: '',
  password: '',
  orId: []
})

//修改表单对象
const updateForm = ref()
const updateData: FormDataType = reactive({
  id: '',
  userCode: '',
  userName: '',
  nickName: '',
  userType: '',
  idCard: '',
  mobile: '',
  phone: '',
  eMail: '',
  orId: []
})

//表格对象
const table = ref()

//树配置项
const orgTreeProps = {
  label: 'orgName',
  isLeaf: 'isLeaf'
}

var treeData: OrgTreeDataType[] = [
  {
    id: 'root',
    parentId: '',
    orgName: t('rbac.org.orgRoot'),
    isLeaf: false
  }
]

const initParams = (data: OrgTreeDataType) => {
  queryFormType.orgId.value = data.id
  orgName.value = data.orgName
  initData.value.orgId = data.id
  loadOrgRole(data.id)
}

//树的点击事件
const clickTreeNode = (data: OrgTreeDataType) => {
  initParams(data)
  flushed()
}

const title = computed(() => {
  return orgName.value + '(' + queryFormType.orgId.value + ')'
})

//加载树代码
const loadNode = async (
  node: Node,
  resolve: (data: OrgTreeDataType[]) => void,
  reject: () => void
) => {
  if (node.level == 0) {
    const userTypeId = userStore.getUserInfo?.userType.id
    if (userTypeId == 'administrator') {
      initParams(treeData[0])
      return resolve(treeData)
    } else {
      const queryOrg = userStore.getUserInfo?.queryOrg as OrgTreeDataType
      expandedKeys.value = [queryOrg.id]
      initParams(queryOrg)
      queryOrg.isLeaf = false
      queryOrg.isParent = true
      return resolve([queryOrg])
    }
  }
  const rs = await getTreeChildApi({ parentId: node.data.id })
  if (rs.success) {
    return resolve(rs.data)
  } else {
    return reject()
  }
}

const queryFormType: QueryFormType = {
  orgId: {
    value: 'root',
    clear: false
  },
  userName: {
    value: '',
    suffix: false,
    queryType: QueryType.LIKE
  },
  userState: {
    value: '',
    queryType: QueryType.EQ
  },
  idCard: {
    value: '',
    suffix: false,
    queryType: QueryType.LIKE_R
  }
}

const loadUserType = async () => {
  const rs = await listApi({})
  if (rs.success) {
    options.value = rs.data
  }
}
//加载用户类型
loadUserType()

const update = (id: string) => {
  updateForm.value.show({ id })
}
const check = async (id: string) => {
  const rs = await checkstateApi(id)
  if (rs.success) {
    table.value.load()
  }
}

//绑定表单对象
const bindForm = ref()
const bindData: FormDataType = {
  userId: '',
  resId: []
}
const bind = (userId: string) => {
  bindForm.value.show({ userId })
}

const resources = ref<ResourceType[]>([])

//加载可以配置的资源
const loadResource = async () => {
  const rs = await listResourceApi()
  if (rs.success) {
    resources.value = rs.data
  }
}
loadResource()

const orgRoleList = ref<OrgRoleType[]>([])
//加载可以配置的资源
const loadOrgRole = async (orgId) => {
  const rs = await getOrgRoleList({ orgId })
  if (rs.success) {
    orgRoleList.value = rs.data
  }
}

const flushed = () => {
  table.value.load(1)
}
</script>

<style scoped></style>
